package com.iakuil.app.common.restful;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.iakuil.app.common.core.DictEnum;
import com.iakuil.app.common.core.jackson.ChinaStyleTimeModule;
import com.iakuil.app.common.core.jackson.DictEnumSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;

import java.util.Locale;
import java.util.TimeZone;

/**
 * JSON自动配置
 *
 * @author Kai
 */
@AutoConfiguration
public class JsonAutoConfiguration {

    @Value("${spring.jackson.date-format:" + DatePattern.NORM_DATETIME_PATTERN + "}")
    private String dateFormatPattern;

    /**
     * Jackson配置
     */
    @Bean
    @ConditionalOnMissingBean
    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
        return builder -> builder.locale(Locale.CHINA)
            .timeZone(TimeZone.getDefault())
            .simpleDateFormat(dateFormatPattern)
            .modules(new ChinaStyleTimeModule())

            .serializerByType(Long.class, ToStringSerializer.instance)
            .serializerByType(DictEnum.class, DictEnumSerializer.instance)

            .serializationInclusion(JsonInclude.Include.NON_NULL)
            .failOnUnknownProperties(false)
            .featuresToEnable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)
            .featuresToDisable(
                JsonGenerator.Feature.IGNORE_UNKNOWN,
                MapperFeature.DEFAULT_VIEW_INCLUSION,
                SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
            );
    }
}
